package ltd.newbee.mall.service.impl;

import ltd.newbee.mall.dao.RoleMapper;
import ltd.newbee.mall.dao.UserMapper;
import ltd.newbee.mall.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RoleMapper roleMapper;

    public List<User> getUserList(Map<String, Object> params) {
        List<User> users = userMapper.selectUserList(params);
        // 为每个用户设置角色信息
        users.forEach(user -> {
            List<Long> roleIds = userMapper.selectRoleIdsByUserId(user.getAdminUserId());
            user.setRoleIds(roleIds);
        });
        return users;
    }

    public User getUserById(Long userId) {
        User user = userMapper.selectUserById(userId);
        if (user != null) {
            List<Long> roleIds = userMapper.selectRoleIdsByUserId(userId);
            user.setRoleIds(roleIds);
        }
        return user;
    }

    @Transactional
    public boolean addUser(User user) {
        // 检查用户名是否重复
        User existingUser = userMapper.selectUserByUserName(user.getLoginUserName());
        if (existingUser != null) {
            throw new RuntimeException("用户名已存在");
        }

        // 添加用户
        int result = userMapper.insertUser(user);
        if (result > 0 && user.getRoleIds() != null && !user.getRoleIds().isEmpty()) {
            // 添加用户角色关联
            userMapper.batchInsertUserRole(user.getAdminUserId(), user.getRoleIds());
        }
        return result > 0;
    }

    @Transactional
    public boolean updateUser(User user) {
        // 检查用户名是否重复（排除自己）
        User existingUser = userMapper.selectUserByUserName(user.getLoginUserName());
        if (existingUser != null && !existingUser.getAdminUserId().equals(user.getAdminUserId())) {
            throw new RuntimeException("用户名已存在");
        }

        // 更新用户信息
        int result = userMapper.updateUser(user);
        if (result > 0) {
            // 更新用户角色
            userMapper.deleteUserRoleByUserId(user.getAdminUserId());
            if (user.getRoleIds() != null && !user.getRoleIds().isEmpty()) {
                userMapper.batchInsertUserRole(user.getAdminUserId(), user.getRoleIds());
            }
        }
        return result > 0;
    }

    @Transactional
    public boolean deleteUser(Long userId) {
        // 删除用户角色关联
        userMapper.deleteUserRoleByUserId(userId);
        // 删除用户
        return userMapper.deleteUser(userId) > 0;
    }

    @Transactional
    public boolean batchDeleteUsers(Long[] userIds) {
        for (Long userId : userIds) {
            userMapper.deleteUserRoleByUserId(userId);
        }
        return userMapper.batchDeleteUser(userIds) == userIds.length;
    }

    public boolean updateUserRoles(Long userId, List<Long> roleIds) {



        userMapper.deleteUserRoleByUserId(userId);
        if (roleIds != null && !roleIds.isEmpty()) {
            userMapper.batchInsertUserRole(userId, roleIds);
        }
        return true;
    }

    public boolean hasUserRole(Long userId,Long roleId) {
        int count = userMapper.countUserRoles(userId,roleId);
        return count > 0;
    }
}
